<template>
  <div class="ticket-list-container">
    <div class="page-header">
      <h2>票种管理</h2>
      <div class="header-actions">
        <el-button :loading="loading" icon="Refresh" type="primary" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <div class="filter-container">
      <el-card>
        <div class="filter-form">
          <el-form :inline="true" :model="queryParams" class="demo-form-inline">
            <el-form-item label="活动名称">
              <el-select
                  v-model="queryParams.eventId"
                  clearable
                  placeholder="选择活动"
                  style="width: 220px"
              >
                <el-option
                    v-for="item in eventOptions"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="票种名称">
              <el-input v-model="queryParams.name" clearable placeholder="票种名称" style="width: 200px"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <div class="ticket-list-content">
      <el-card v-loading="loading">
        <template #header>
          <div class="card-header">
            <span>票种列表</span>
            <el-button v-if="isAdmin" size="small" type="primary" @click="goToAddTicket">添加票种</el-button>
          </div>
        </template>

        <el-table
            v-loading="loading"
            :data="ticketList"
            border
            row-key="id"
            style="width: 100%"
        >
          <!-- 当数据为空时的展示 -->
          <template #empty>
            <el-empty description="暂无票种数据"/>
          </template>

          <el-table-column type="expand">
            <template #default="props">
              <div class="ticket-detail-expand">
                <el-descriptions :column="3" border>
                  <el-descriptions-item label="票种ID">{{ props.row.id }}</el-descriptions-item>
                  <el-descriptions-item label="创建时间">{{ props.row.createdAt }}</el-descriptions-item>
                  <el-descriptions-item label="更新时间">{{ props.row.updatedAt }}</el-descriptions-item>
                  <el-descriptions-item :span="3" label="票种说明">
                    {{ props.row.description || '暂无说明' }}
                  </el-descriptions-item>
                </el-descriptions>

                <div v-if="props.row.statsLoaded" class="sales-stats">
                  <h4>销售数据</h4>
                  <el-progress
                      :percentage="Math.floor((props.row.soldCount / props.row.totalStock) * 100)"
                      :status="getProgressStatus(props.row.soldCount, props.row.totalStock)"
                  />
                  <div class="stats-details">
                    <el-tag>已售: {{ props.row.soldCount }}</el-tag>
                    <el-tag type="success">剩余: {{ props.row.totalStock - props.row.soldCount }}</el-tag>
                    <el-tag type="warning">销售额: ¥{{ (props.row.soldCount * props.row.price).toFixed(2) }}</el-tag>
                  </div>
                </div>
                <div v-else class="sales-stats">
                  <el-button size="small" @click="loadTicketStats(props.row)">加载销售数据</el-button>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="所属活动" min-width="160" prop="eventTitle" show-overflow-tooltip/>
          <el-table-column label="票种名称" min-width="120" prop="name"/>
          <el-table-column label="价格" min-width="100" prop="price">
            <template #default="scope">
              <span>¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总库存" min-width="80" prop="totalStock"/>
          <el-table-column label="已售" min-width="80" prop="soldCount"/>
          <el-table-column label="限购" min-width="80" prop="limitPerUser"/>
          <el-table-column label="状态" min-width="100">
            <template #default="scope">
              <el-tag :type="scope.row.eventStatus === 'online' ? 'success' : 'info'">
                {{ getEventStatusText(scope.row.eventStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button-group>
                <el-button
                    size="small"
                    type="primary"
                    @click="goToEventDetail(scope.row.eventId)"
                >
                  查看活动
                </el-button>

              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
              v-model:currentPage="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useUserStore} from '@/store/user'
import {deleteTicket, getTicketList, getTicketStats} from '@/api/ticket'
import {getEventList} from '@/api/event'

const router = useRouter()
const userStore = useUserStore()

// 判断是否为管理员
const isAdmin = computed(() => userStore.role === 'admin')
const userId = computed(() => userStore.userId)

// 数据加载状态
const loading = ref(false)

// 活动选项
const eventOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  eventId: undefined,
  name: ''
})

// 票种列表数据
const ticketList = ref([])
const total = ref(0)

// 调试模式
const DEBUG_MODE = false

// 初始化
onMounted(async () => {
  try {
    await fetchEventOptions()
    await fetchTicketList()
  } catch (error) {
    console.error('初始化过程出错:', error)
  }
})

// 获取活动选项
const fetchEventOptions = async () => {
  try {
    // 调用活动列表API，获取所有活动作为选项
    const response = await getEventList({pageSize: 100})
    if (response.code === 200 && response.data) {
      eventOptions.value = response.data.list || []
    }
  } catch (error) {
    console.error('获取活动选项出错:', error)
    ElMessage.error('获取活动选项失败')
  }
}

// 获取票种列表
const fetchTicketList = async () => {
  loading.value = true

  try {
    // 如果选择了特定活动，则获取该活动的票种
    if (queryParams.eventId) {
      const res = await getTicketList(queryParams.eventId)

      if (res.code === 200) {
        // 处理票种数据，添加活动信息
        const eventInfo = eventOptions.value.find(e => e.id === parseInt(queryParams.eventId)) || {}

        ticketList.value = (res.data || []).map(ticket => ({
          ...ticket,
          eventTitle: eventInfo.title || '未知活动',
          eventStatus: eventInfo.status || 'unknown',
          statsLoaded: false
        }))

        // 如果有名称筛选，进行前端过滤
        if (queryParams.name) {
          ticketList.value = ticketList.value.filter(t =>
              t.name.toLowerCase().includes(queryParams.name.toLowerCase())
          )
        }

        total.value = ticketList.value.length
      } else {
        ElMessage.error(res.msg || '获取票种列表失败')
        ticketList.value = []
      }
    } else {
      // 如果没有选择特定活动，则聚合所有活动的票种
      let allTickets = []

      // 首先尝试直接获取所有票种（如果后端支持）
      try {
        // 直接从活动列表获取所有票种，而不是调用getTicketList('all')
        // 避免后端API不支持的GET请求
        const allEvents = eventOptions.value || []

        // 获取所有活动的票种（有数据的活动）
        for (const event of allEvents) {
          // 只处理有票种的活动
          if (event.ticketCount > 0) {
            try {
              const res = await getTicketList(event.id)

              if (res.code === 200 && res.data) {
                const eventTickets = res.data.map(ticket => ({
                  ...ticket,
                  eventTitle: event.title || '未知活动',
                  eventStatus: event.status || 'unknown',
                  statsLoaded: false
                }))

                allTickets = [...allTickets, ...eventTickets]
              }
            } catch (error) {
              console.error(`获取活动 ${event.id} 票种出错:`, error)
            }
          }
        }
      } catch (error) {
        console.error('获取所有票种失败:', error)
      }

      // 如果有名称筛选，进行前端过滤
      if (queryParams.name) {
        allTickets = allTickets.filter(t =>
            t.name.toLowerCase().includes(queryParams.name.toLowerCase())
        )
      }

      // 分页处理
      const start = (queryParams.pageNum - 1) * queryParams.pageSize
      const end = start + queryParams.pageSize

      total.value = allTickets.length
      ticketList.value = allTickets.slice(start, end)
    }
  } catch (error) {
    console.error('获取票种列表出错:', error)
    ElMessage.error('获取票种列表失败')
    ticketList.value = []
  } finally {
    loading.value = false
  }
}

// 加载票种销售数据
const loadTicketStats = async (row) => {
  try {
    const res = await getTicketStats(row.id)
    if (res.code === 200 && res.data) {
      // 更新票种列表中的销售数据
      const index = ticketList.value.findIndex(t => t.id === row.id)
      if (index !== -1) {
        ticketList.value[index] = {
          ...ticketList.value[index],
          ...res.data,
          statsLoaded: true
        }
      }
    } else {
      ElMessage.warning('获取销售数据失败')
    }
  } catch (error) {
    console.error('加载票种销售数据出错:', error)
    ElMessage.error('加载销售数据失败')
  }
}

// 根据销售比例获取进度条状态
const getProgressStatus = (sold, total) => {
  const percentage = sold / total
  if (percentage >= 0.8) return 'warning'
  if (percentage >= 1) return 'exception'
  return 'success'
}

// 获取活动状态文本
const getEventStatusText = (status) => {
  const statusMap = {
    'draft': '草稿',
    'online': '已发布',
    'offline': '已下线',
    'unknown': '未知'
  }
  return statusMap[status] || '未知'
}

// 判断是否可以编辑票种
const canEditTicket = (row) => {
  // 管理员或活动创建者可以编辑票种，且活动不能是已下线状态
  const isOwner = row.createdBy === userId.value
  return (isAdmin.value || isOwner) && row.eventStatus !== 'offline' && row.soldCount === 0
}

// 查询按钮点击事件
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchTicketList()
}

// 重置查询按钮点击事件
const resetQuery = () => {
  queryParams.eventId = undefined
  queryParams.name = ''
  queryParams.pageNum = 1
  fetchTicketList()
}

// 刷新数据
const refreshData = () => {
  fetchTicketList()
}

// 跳转到活动详情
const goToEventDetail = (eventId) => {
  router.push(`/event/detail/${eventId}`)
}

// 跳转到添加票种页面
const goToAddTicket = () => {
  // 如果选择了活动，则直接跳转到该活动的详情页
  if (queryParams.eventId) {
    router.push(`/event/detail/${queryParams.eventId}`)
  } else {
    // 否则提示用户先选择活动
    ElMessage.info('请先选择一个活动，才能添加票种')
  }
}

// 删除票种
const handleDeleteTicket = async (row) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除该票种吗？此操作不可恢复。',
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    loading.value = true
    const res = await deleteTicket(row.eventId, row.id)

    if (res.code === 200) {
      ElMessage.success('删除票种成功')
      fetchTicketList()
    } else {
      ElMessage.error(res.msg || '删除票种失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除票种出错:', error)
      ElMessage.error('删除票种失败')
    }
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchTicketList()
}

// 页码改变
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchTicketList()
}
</script>

<style scoped>
.ticket-list-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #4d7aff);
  margin-right: 12px;
  border-radius: 2px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.ticket-list-content {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 500;
}

.ticket-detail-expand {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.sales-stats {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #ddd;
}

.sales-stats h4 {
  margin-top: 0;
  margin-bottom: 10px;
}

.stats-details {
  margin-top: 16px;
  display: flex;
  gap: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 调试信息区域样式 */
.debug-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px dashed #ccc;
}

.debug-info p {
  margin: 5px 0;
  font-family: monospace;
}

.debug-info pre {
  margin: 10px 0;
  padding: 10px;
  background-color: #eee;
  border-radius: 4px;
  overflow: auto;
  max-height: 300px;
}

@media (max-width: 768px) {
  .filter-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }
}

:deep(.el-button--primary) {
  background: #5e5ce6;
  border-color: #5e5ce6;
}

:deep(.el-button--primary:hover) {
  background: #6b69e3;
  border-color: #6b69e3;
}
</style> 